package me.zhengjie.modules.supplier_app.rest;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.aop.log.Log;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.monitor.service.RedisService;
import me.zhengjie.modules.security.security.AuthenticationInfo;
import me.zhengjie.modules.security.security.AuthenticationObject;
import me.zhengjie.modules.security.security.AuthorizationUser;
import me.zhengjie.modules.security.security.JwtUser;
import me.zhengjie.modules.security.utils.JwtTokenUtil;
import me.zhengjie.modules.serviceprovider.domain.TServiceproviderPerson;
import me.zhengjie.modules.serviceprovider.service.TServiceproviderPersonService;
import me.zhengjie.modules.serviceprovider.service.dto.TServiceproviderPersonDTO;
import me.zhengjie.utils.HttpResponseUtils;
import me.zhengjie.utils.SecurityUtils;
import me.zhengjie.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;

/**
 * Created by bruce on 19/11/14.
 */
@Slf4j
@RestController
@RequestMapping("app")
public class TAppSupplierAuthController {
    @Autowired
    private RedisService redisService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    @Qualifier("jwtSupplierUserDetailsService")
    private UserDetailsService supplierUserDetailsService;

    @Autowired
    private TServiceproviderPersonService personService;

    /**tappsu
     * 验证密码
     * @param authorizationUser
     * @return
     */
    @Log("服务商登录")
    @PostMapping(value = "/supplier/login")
    public ResponseEntity login(@Validated @RequestBody AuthorizationUser authorizationUser){
        /*
        // 查询验证码
        String code = redisService.getCodeVal(authorizationUser.getUuid());
        // 清除验证码
        redisService.delete(authorizationUser.getUuid());
        if (StringUtils.isBlank(code)) {
            throw new BadRequestException("验证码已过期");
        }
        if (StringUtils.isBlank(authorizationUser.getCode()) || !authorizationUser.getCode().equalsIgnoreCase(code)) {
            throw new BadRequestException("验证码错误");
        }*/
        final JwtUser jwtUser = (JwtUser) supplierUserDetailsService.loadUserByUsername(authorizationUser.getUsername());

        //if(!jwtUser.getPassword().equals(EncryptUtils.encryptPassword(authorizationUser.getPassword()))){
        if(!jwtUser.getPassword().equals(authorizationUser.getPassword())){
            throw new AccountExpiredException("密码错误");
        }

        if(!jwtUser.isEnabled()){
            throw new AccountExpiredException("账号已停用，请联系管理员");
        }

        // 生成令牌
        final String token = jwtTokenUtil.generateToken(jwtUser);

        JSONObject object = new JSONObject();
        object.put("id", jwtUser.getId());
        object.put("username", jwtUser.getUsername());
        object.put("password",jwtUser.getPassword());
        object.put("avatar",jwtUser.getPassword());
        object.put("email",jwtUser.getPassword());
        object.put("phone",jwtUser.getPhone());
        object.put("dept",jwtUser.getDept());
        object.put("job",jwtUser.getJob());
        object.put("authorities",new ArrayList<GrantedAuthority>());
        object.put("enabled",jwtUser.isEnabled());
        object.put("createTime",jwtUser.getCreateTime());
        object.put("isAdmin",jwtUser.getIsAdmin());
        object.put("name",jwtUser.getName());
        object.put("ownerId",jwtUser.getOwnerId());
        object.put("ownerName",jwtUser.getOwnerName());


        TServiceproviderPersonDTO personDTO = personService.findById(jwtUser.getId());
        object.put("country",personDTO.getCountry());
        object.put("province",personDTO.getProvince());
        object.put("city",personDTO.getCity());
        object.put("county",personDTO.getCounty());
        object.put("major",personDTO.getMajor());
        object.put("level",personDTO.getLevel());

        // 返回 token
        return ResponseEntity.ok(new AuthenticationObject(token,object));
    }

    /**
     * 验证密码
     * @param object
     * @return
     */
    @Log("服务商登录")
    @PostMapping(value = "/supplier/reset")
    public ResponseEntity reset(@RequestBody JSONObject object){
        // 密码
        String password = object.getString("password");
        String newPass  = object.getString("newPass");
        if(StringUtils.isEmpty(password) || StringUtils.isEmpty(newPass)) {
            throw new BadRequestException("密码信息不能为空");
        }
        String userName = SecurityUtils.getUsername();
        final JwtUser jwtUser = (JwtUser) supplierUserDetailsService.loadUserByUsername(userName);

        if(!jwtUser.getPassword().equals(password)){
            throw new AccountExpiredException("密码错误");
        }

        if(!jwtUser.isEnabled()){
            throw new AccountExpiredException("账号已停用，请联系管理员");
        }

        TServiceproviderPersonDTO personDTO = personService.findByUsername(userName);
        if(!personDTO.getPersonPassword().equals(password)){
            throw new AccountExpiredException("密码错误");
        }

        TServiceproviderPerson personUpdate = new TServiceproviderPerson();
        BeanUtils.copyProperties(personDTO, personUpdate);
        personUpdate.setPersonPassword(newPass);
        personService.update(personUpdate);

        return HttpResponseUtils.passDefaultResponse("修改成功", HttpStatus.OK);
    }
}
